﻿using System;
using System.Text;

namespace HoangPhap.Utilities
{
    public class RandomStrings
    {
        private const int ConstMaxStringLenght = 10;
        private const string ConstAllowedCharacterLiterals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

        private readonly Random _randomNumber = new Random();

        public string GenerateRandomString()
        {
            return GenerateRandomString(ConstMaxStringLenght);
        }

        public string GenerateRandomString(int lenght)
        {
            return GenerateRandomString(lenght, CreateRandomStringSet());
        }

        public string GenerateRandomString(DateTime d)
        {
            var util = new Common();
            return util.DateTimeToNum() + GenerateRandomString(0) + GenerateRandomString(0) + GenerateRandomString(0) + GenerateRandomString(0);
        }

        public string GenerateRandomString(int lenght, string charsToUse, bool randomizeSourceSet)
        {
            return GenerateRandomString(lenght, randomizeSourceSet ? CreateRandomStringSet(charsToUse) : charsToUse);
        }

        public string GenerateRandomString(int lenght, string charsToUse)
        {
            var randomString = new StringBuilder();

            for (var i = 0; i <= lenght; i++)
            {
                var characterIndex = Convert.ToInt32(_randomNumber.Next(i, charsToUse.Length - i));
                var appendedChar = charsToUse[characterIndex];

                randomString.Append(appendedChar);
            }
            return randomString.ToString();
        }

        private string CreateRandomStringSet(string allowedCharacters = ConstAllowedCharacterLiterals)
        {
            var randomizedString = String.Empty;
            var randomSetLenght = allowedCharacters.Length * _randomNumber.Next(1, ConstMaxStringLenght);

            while (randomizedString.Length != randomSetLenght)
            {
                randomizedString += GetRandomCharFromString(allowedCharacters);
            }

            return randomizedString;
        }

        private char GetRandomCharFromString(string allowedCharacters)
        {
            return allowedCharacters[_randomNumber.Next(allowedCharacters.Length - 1)];
        }

    }
}